/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package users.tag;

import java.util.Collection;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import tracker.TrackerHelper;
import tracker.Users;

/**
 *
 * @author El Desperado
 */
public class LoginTagHandler extends TagSupport {

    private String userName;
    private String password;

    @Override
    public int doStartTag() throws JspException {
        return super.doStartTag();
    }

    @Override
    public int doEndTag() throws JspException {
        System.err.println("Username: " + userName);
        System.err.println("Password: " + password);
        Pattern p = Pattern.compile("^[A-Za-z0-9]+$");
        Matcher m = p.matcher(userName);
        if (m.matches()) {
            try {
                TrackerHelper helper = new TrackerHelper();
                Collection<Users> list = helper.getUserByName(userName);
                Iterator<Users> it = list.iterator();
                while (it.hasNext()) {
                    Users usr = it.next();
                    if (usr.getUserName().equals(userName)) {
                        if (usr.getPassword().equals(password)) {
                            Cookie ck = new Cookie("accNumber", userName);
                            System.out.println("Login Successfully! Username: " + userName + " Password: " + password);

                            return 0;
                        } else {
                            System.out.println("Login Failed! Username: " + userName + " Password: " + password);
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println("Error in LoginTag: " + e.getMessage());
            }
        }
        return EVAL_PAGE;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
